package mx.kolobok.noteeditor.ui.list;

import mx.kolobok.noteeditor.Note;
import mx.kolobok.noteeditor.NoteManager;
import mx.kolobok.noteeditor.NoteManagerException;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.List;

/**
 * User:  Nikita Belenkiy
 * Date: 24.05.11
 * Time: 18:24
 */
public class NoteListModel extends AbstractListModel {

    private static final Logger logger = Logger.getLogger(NoteListModel.class);

    private NoteManager noteManager;

    public NoteListModel(NoteManager noteManager) {
        this.noteManager = noteManager;
    }

    @Override
    public int getSize() {
        return noteManager.getNotes().size();
    }

    @Override
    public Object getElementAt(int index) {
        return noteManager.getNotes().get(index);
    }

    public void deleteNote(int noteNumber) throws NoteManagerException {
        Note note = noteManager.deleteNote(noteNumber);
        fireIntervalRemoved(note, noteNumber - 1, noteNumber);
    }


    @NotNull
    public Note createDefaultNote() throws NoteManagerException {
        return createNewNote("Note title", "Note text");
    }

    @NotNull
    public Note createNewNote(String title, String text) throws NoteManagerException {
        List<Note> notes = noteManager.getNotes();
        int size = notes.size();
        for (int i = 0; i < size; i++) {
            Note note = notes.get(i);
            //means note has never been updated
            if (note.getCreated().equals(note.getUpdated())) {
                logger.debug("default note already exists");
                fireContentsChanged(this, i, i);
                return note;
            }
        }

        Note note = noteManager.createNote(title, text);

        logger.debug("added new Note");
        fireIntervalAdded(this, getSize() - 1, getSize() - 1);
        return note;
    }


    public void moveNoteToPosition(Note note, int newIndex) throws NoteManagerException {
        int i = noteManager.moveToPosition(note, newIndex);
        if (i != newIndex) {
            fireContentsChanged(this, Math.min(i,newIndex), Math.max(i,newIndex));
        }
    }
}
